package com.webside.points.wechat;

import java.io.File;
import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import java.util.UUID;

import javax.xml.parsers.ParserConfigurationException;

import org.xml.sax.SAXException;

import it.sauronsoftware.jave.AudioAttributes;
import it.sauronsoftware.jave.Encoder;
import it.sauronsoftware.jave.EncoderException;
import it.sauronsoftware.jave.EncodingAttributes;



public class WxPayApi {

	
	/**
	 * 
	 * 查询订单
	 * 
	 * @param WxPayData
	 *            inputObj 提交给查询订单API的参数
	 * @param int timeOut 超时时间
	 * @throws WxPayException
	 * @return 成功时返回订单查询结果，其他抛异常
	 * @throws NoSuchAlgorithmException
	 * @throws IOException
	 * @throws SAXException
	 * @throws ParserConfigurationException
	 */
	public static WxPayData OrderQuery(WxPayData inputObj, int timeOut)
			throws WxPayException, NoSuchAlgorithmException,
			ParserConfigurationException, SAXException, IOException {
		timeOut = (timeOut == 0 ? 6 : timeOut);
		String url = "https://api.mch.weixin.qq.com/pay/orderquery";
		// 检测必填参数
		if (!inputObj.IsSet("out_trade_no")
				&& !inputObj.IsSet("transaction_id")) {
			throw new WxPayException(
					"订单查询接口中，out_trade_no、transaction_id至少填一个！");
		}

		inputObj.SetValue("appid", WeChatConfig.APP_ID);// 公众账号ID
		inputObj.SetValue("mch_id", WeChatConfig.MCH_ID);// 商户号
		inputObj.SetValue("nonce_str", GenerateNonceStr());// 随机字符串
		inputObj.SetValue("sign", inputObj.MakeSign("MD5"));// 签名

		String xml = inputObj.ToXml();

		//long start = System.currentTimeMillis();

		String response = HttpUtil.sendPost(url,xml, false, timeOut);// 调用HTTP通信接口提交数据

		//long end = System.currentTimeMillis();
		//int timeCost = (int) ((end - start));// 获得接口耗时

		// 将xml格式的数据转化为对象以返回
		WxPayData result = new WxPayData();
		result.FromXml(response);

		//ReportCostTime(url, timeCost, result ,request);// 测速上报

		return result;
	}
	
	/**
	 * 生成随机串，随机串包含字母或数字
	 * 
	 * @return 随机串
	 */
	public static String GenerateNonceStr() {
		return UUID.randomUUID().toString().replaceAll("-", "");
	}
	
	
	//音频转换
	public static Boolean change(String agoPath,String laterPath) {
		File source = new File(agoPath);
		File target = new File(laterPath);
		AudioAttributes audio = new AudioAttributes();
		Encoder encoder = new Encoder();

		audio.setCodec("libmp3lame");
		EncodingAttributes attrs = new EncodingAttributes();
		attrs.setFormat("mp3");
		attrs.setAudioAttributes(audio);
		
		try {
			encoder.encode(source, target, attrs);
			return true;
		} catch (EncoderException e) {
			//e.printStackTrace();
			return true;
		}
	}
	
	
}
